# -*- coding: utf-8 -*-
from typing   import get_args
from datetime import datetime

from src       import utils
from src.types import Region, WeatherForecast, WEATHER_CONDITION

from fastapi           import Request, APIRouter, HTTPException
from fastapi.responses import Response, JSONResponse


region_weather_forecast = APIRouter(prefix = "/forecast", dependencies = [utils.check.has_auth()])


@region_weather_forecast.get("/{forecastld}")
async def region_weather_forecast_get(request: Request, forecastld: int):
    if forecastld == None or 0 >= forecastld:
        raise HTTPException(400, detail = "Invalid ID")

    forecast = await WeatherForecast.get_by(request.app.database, id = forecastld)

    if not forecast:
        raise HTTPException(404, detail = "The forecast with this ID was not found")
    return JSONResponse(forecast("id", "dateTime", "temperature", "weatherCondition", "regionId"), status_code = 200)


@region_weather_forecast.post("/")
async def region_weather_forecast_add(request: Request):
    data: dict = await utils.parse.dictionary(request = request)

    if not data:
        raise HTTPException(400, detail = "Failed to get passed values, specify them in JSON format")

    if (data.get("regionId") == None) or (0 >= data.get("regionId")):
        raise HTTPException(400, detail = "Incorrect regionId")

    try:
        datetime.fromisoformat(data['dateTime'])
    except:
        raise HTTPException(400, detail = "Incorrect dateTime")

    if data.get("weatherCondition") not in get_args(WEATHER_CONDITION):
        raise HTTPException(400, detail = "Incorrect weatherCondition")

    exists = await Region.exists(request.app.database, id = data.get("regionId"))

    if not exists:
        raise HTTPException(404, detail = 'The region with this regionId was not found')

    forecast = await WeatherForecast.create(request.app.database, **data)
    return JSONResponse(forecast("id", "regionId", "temperature", "weatherCondition", "dateTime"), status_code = 200)


@region_weather_forecast.put("/{forecastld}")
async def region_weather_forecast_change(request: Request, forecastld: int):
    if forecastld == None or 0 >= forecastld:
        raise HTTPException(400, detail = "Invalid ID")

    data: dict = await utils.parse.dictionary(request = request)

    if not data:
        raise HTTPException(400, detail = "Failed to get passed values, specify them in JSON format")

    try:
        datetime.fromisoformat(data['dateTime'])
    except:
        raise HTTPException(400, detail = "Incorrect dateTime")

    if data.get("weatherCondition") not in get_args(WEATHER_CONDITION):
        raise HTTPException(400, detail = "Incorrect weatherCondition")

    forecast = await WeatherForecast.get_by(request.app.database, id = forecastld)

    if not forecast:
        raise HTTPException(404, detail = "The forecast with this ID was not found")

    await forecast.update(**data)
    return JSONResponse(forecast("id", "dateTime", "temperature", "weatherCondition", "regionId"), status_code = 200)


@region_weather_forecast.delete("/{forecastld}")
async def region_weather_forecast_delete(request: Request, forecastld: int):
    if forecastld == None or 0 >= forecastld:
        raise HTTPException(400, detail = "Invalid ID")

    forecast = await WeatherForecast.get_by(request.app.database, id = forecastld)
    await forecast.delete()

    return Response(None)
